package com.example.controller;

import com.example.entity.RestBean;
import com.example.service.AuthorizeService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author AiXu
 * @version v1.0
 * @since 2023/9/12 11:53
 */

@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {

    private final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    private final String USERNAME_REGEX = "^[\\u4e00-\\u9fa5A-Za-z]+$";

    @Resource
    AuthorizeService service;

    @PostMapping("/valid-register-email")
    public RestBean<Void> validateRegisterEmail(@Pattern(regexp = EMAIL_REGEX)
                                                @RequestParam("email") String email,
                                                HttpSession session) {
        String validatedEmail = service.sendValidatedEmail(email, session.getId(), false);
        if (validatedEmail == null) {
            return RestBean.success(null, "邮件已发送，注意查收");
        } else {
            return RestBean.failure(400, validatedEmail);
        }
    }

    @PostMapping("/valid-reset-email")
    public RestBean<Void> validateResetEmail(@Pattern(regexp = EMAIL_REGEX)
                                             @RequestParam("email") String email,
                                             HttpSession session) {
        String validatedEmail = service.sendValidatedEmail(email, session.getId(), true);
        if (validatedEmail == null) {
            return RestBean.success(null, "邮件已发送，注意查收");
        } else {
            return RestBean.failure(400, validatedEmail);
        }
    }

    @PostMapping("/register")
    public RestBean<String> registerUser(
            @Pattern(regexp = USERNAME_REGEX) @Length(max = 8, min = 2)
            @RequestParam("username") String username,
            @Length(max = 16, min = 6)
            @RequestParam("password") String password,
            @Pattern(regexp = EMAIL_REGEX)
            @RequestParam("email") String email,
            @Length(max = 6, min = 6)
            @RequestParam("code") String code,
            HttpSession session) {

        String register = service.validateAndRegister(username, password, email, code, session.getId());
        if (register == null) {
            return RestBean.success(null, "注册成功");
        } else {
            return RestBean.failure(400, register);
        }
    }

    /**
     * 1. 发验证邮件
     * 2. 验证码是否正确，正确就在Session中存标记
     * 3. 用户发起重置密码请求，如果存在标记就成功重置
     *
     * @return
     */
    @PostMapping("/start-reset")
    public RestBean<String> startReset(
            @RequestParam("email") String email,
            @Length(max = 6, min = 6)
            @RequestParam("code") String code,
            HttpSession session) {
        String s = service.validateOnly(email, code, session.getId());
        if (s == null) {
            session.setAttribute("reset-password", email);
            return RestBean.success(null, "验证成功");
        } else return RestBean.failure(400, s);
    }

    @PostMapping("/do-reset")
    public RestBean<String> restPassword(@Length(max = 16, min = 6)
                                         @RequestParam("password") String password, HttpSession session) {
        String email = (String) session.getAttribute("reset-password");
        if (email == null) {
            return RestBean.failure(401, "请先完成邮箱验证");
        } else if (service.resetPassword(email, password)) {
            session.removeAttribute("reset-password");
            return RestBean.success(null, "密码重置成功");
        } else return RestBean.failure(500);
    }
}
